gh-102699: Add dataclasses.DataclassLike#102933
gh-102699: Add dataclasses.DataclassLike#102933AlexWaygood wants to merge 11 commits intopython:mainfrom
dataclasses.DataclassLike#102933Conversation
Lib/dataclasses.py
Outdated
| # __dataclass_fields__ here is really an "abstract class variable", | ||
| # but there's no good way of expressing that at runtime, | ||
| # so just make it a regular class variable with a dummy value | ||
| __dataclass_fields__ = {} |
There was a problem hiding this comment.
Why do we need this? In my opinion, def __subclasshook__(cls, other): is enough.
For example, your own tests do not use this attribute.
There was a problem hiding this comment.
Without this attribute, the abstract base class for all dataclasses would not itself be considered a dataclass by the dataclasses internal machinery, which would be quite bizarre in my opinion:
>>> from dataclasses import *
>>> is_dataclass(DataclassLike)
True
>>> del DataclassLike.__dataclass_fields__
>>> is_dataclass(DataclassLike)
FalseBut you are correct that this currently isn't covered. I will add a test for this :)
There was a problem hiding this comment.
But, is DataclassLike a dataclass? :)
You can have two opinions here.
There was a problem hiding this comment.
The contract here is that "all classes for which is_dataclass evaluates to True shall be considered subclasses of DataclassLike. But DataclassLike is considered a subclass of DataclassLike (because all classes are considered subclasses of themselves in Python). So it would be very strange, in my opinion, for there to be one class (DataclassLike itself) where is_dataclass(x) evaluates to False but it's nonetheless considered a subclass of DataclassLike.
There was a problem hiding this comment.
Alternatively, I could make DataclassLike an actual dataclass, I suppose? Rather than "faking it". What do you think?
There was a problem hiding this comment.
Do you like it better after adad189? :)
Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
…python into dataclass-protocol
|
The feature freeze is fast approaching now, but here's why I haven't merged this yet:
|
|
This protocol is now available in the third-party |
Add
dataclasses.DataclassLike, an abstract base class for dataclasses. Mainly useful for type-hinting. See the issue for a more complete rationale for why this class would be useful.